﻿/// <reference path="jquery1.js" />

window.$$ = new function () {
	var me = this;

	me.AppVer = "11806070";	//app版本
	me.AppDev = "SA." + me.AppVer + ":" + navigator.userAgent;	//app设备
	jQuery.fn.extend({
		onClick: function (callback) { this.on("click", callback); return this; },
		oneClick: function (callback) { this.one("click", callback); return this; },
		offClick: function () { this.off("click"); return this; }
	});

	//var emptyData = { NONE: true };
	function emptyfunc() { }

	var intRegex = /^[+-]?\d+$/;
	me.ParseInt = function (num) {
		var type = $.type(num);
		if (type === "number") return parseInt(num, 10);
		if (type === "string") {
			if ((num = $.trim(num)).length < 1) return null;
			if (intRegex.test(num)) return parseInt(num, 10);
			return null;
		}
		return null;
	};

	var floatRegex = /^[+-]?\d+(\.\d+)?$/;
	me.ParseFloat = function (num) {
		var type = $.type(num);
		if (type === "number") return parseFloat(num, 10);
		if (type === "string") {
			if ((num = $.trim(num)).length < 1) return null;
			if (floatRegex.test(num)) return parseFloat(num, 10);
			return null;
		}
		return null;
	};

	me.FixNum = function (num, floatcount) {
		var f = me.ParseFloat(num);
		if (!f && f !== 0) return num;
		if (floatcount > 0) return f.toFixed(floatcount);
		return f.toFixed();
	};
	
	me.FixHtml = function (html) {
		if (!html && html !== 0) return "";
		if (html.length < 5) return "";
		return html.replace(/<(style|script|link)/gi, function (m, g1) { return "&lt;" + g1; });
	};

	me.ToStr = function (obj, itemlen) {
		if (!obj) return obj;
		if (!itemlen || itemlen < 1) itemlen = 10;
		var s = [];
		for (var key in obj) {
			//if (!obj.hasOwnProperty(key)) continue;
			s.push(key + "=");
			val = obj[key] + "";
			if (val) s.push(val.substr(0, itemlen));
			s.push("；");
		}
		return s.join("");
	};

	me.Utf16to8 = function (str) {
		var out, i, len, c;
		out = "";
		len = str.length;
		for (i = 0; i < len; i++) {
			c = str.charCodeAt(i);
			if ((c >= 0x0001) && (c <= 0x007F)) {
				out += str.charAt(i);
			} else if (c > 0x07FF) {
				out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
				out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			} else {
				out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			}
		}
		return out;
	};
	me.B64ToBlob = function (b64, mime) {
		if (!b64) return null;
		if (typeof b64 !== "string") return null;
		var idx = b64.indexOf(",", 0);
		if (idx >= 0) b64 = b64.substr(idx + 1);
		b64 = b64.replace(/\s/g, '');
		if (!mime) mime = "application/octet-stream";
		try {
			var binary = window.atob(b64);
			var len = binary.length;
			var buf = new ArrayBuffer(len);
			var view = new Uint8Array(buf);
			for (var i = 0; i < len; i++) {
				view[i] = binary.charCodeAt(i);
			}
			var blob = new Blob([view], { type: mime });
			return blob;
		}
		catch (e) { console.error(e); return null; }
	};
	me.UrlToBlob = function (url, mime, callback) {
		if (!callback) callback = emptyfunc;
		if (!url) { callback(); return; }
		//if (url instanceof Blob) { callback(url); return; }
		if (typeof url == 'object') { callback(url); return; }
		if (typeof url !== "string") { callback(); return; }
		var xhr = new XMLHttpRequest();
		xhr.responseType = "blob";
		xhr.onerror = xhr.onabort = function () { callback(); };
		xhr.onload = function () {
			var blob = xhr.response;
			if (blob instanceof Blob) callback(blob);
			else callback();
		};
		xhr.open("GET", url, true);
		xhr.send();
	};
	me.BlobToUrl = function (b64, mime, callback) {
	    if (!callback) callback = emptyfunc;
	    if (!b64) { callback(); return; }
	    var blob = null;
	    //if (b64 instanceof Blob) blob = b64;
	    if (typeof b64 == 'object') blob = b64;
	    else {
	        blob = me.B64ToBlob(b64, mime);
	        if (!blob) { callback(); return; }
	    }
		if (window.URL) {
			try {
				var url = window.URL.createObjectURL(blob);
				if (url) { callback(url); return; }
			}
			catch (ex) { }
		}

		if (window.FileReader) {
			var reader = new window.FileReader();
			reader.onerror = function () { callback(); };
			reader.onload = function () { callback(reader.result); }
			reader.readAsDataURL(blob);
		}
		else callback();
	};

	//输出日期时间
	//format:输出格式，如yy年mm月dd日，默认yy-mm-dd
	//y：年 16｜yy：全年 2016
	//M：月 3 ｜ MM：补全月 03
	//d：日 9｜dd：补全日 09
	//h：时 9｜hh：补全时 09
	//m：分 9｜mm：补全分 09
	//s：秒 9｜ss：补全秒 09
	me.CalcDate = function (datetime, format) {
		if (!datetime) return "";
		var dt;
		if (datetime instanceof Date) dt = datetime;
		else dt = new Date(datetime);
		if (!dt) return "";

		if (!format) format = "yy-mm-dd";
		var rst = format; var val;
		if (format.indexOf("y") >= 0) {
			val = dt.getFullYear();
			if (format.indexOf("yy") < 0) val = (val + "").substr(2, 2);
			rst = rst.replace(/y+/g, val);
		}

		if (format.indexOf("M") >= 0) {
			val = dt.getMonth() + 1;
			if (val < 10 && format.indexOf("MM") >= 0) val = "0" + val;
			rst = rst.replace(/M+/g, val);
		}

		if (format.indexOf("d") >= 0) {
			val = dt.getDate();
			if (val < 10 && format.indexOf("dd") >= 0) val = "0" + val;
			rst = rst.replace(/d+/g, val);
		}

		if (format.indexOf("h") >= 0) {
			val = dt.getHours();
			if (val < 10 && format.indexOf("hh") >= 0) val = "0" + val;
			rst = rst.replace(/h+/g, val);
		}

		if (format.indexOf("m") >= 0) {
			val = dt.getMinutes();
			if (val < 10 && format.indexOf("mm") >= 0) val = "0" + val;
			rst = rst.replace(/m+/g, val);
		}

		if (format.indexOf("s") >= 0) {
			val = dt.getSeconds();
			if (val < 10 && format.indexOf("ss") >= 0) val = "0" + val;
			rst = rst.replace(/s+/g, val);
		}

		return rst;
	};
	me.CalcAge = function (birthday) {
		if (!birthday || birthday < 19300000) return 0;
		var now = new Date();
		now = now.getFullYear();
		var y = Math.floor(birthday / 10000);
		y = now - y;
		if (y > 80 || y < 16) return 0;
		return y;
	};
	me.MapImage = function (lat, lng, addr) {
		var pos = "";
		if (lat > 0 && lng > 0) pos = lng + "," + lat;
		else if (!addr) pos = window.encodeURI(addr);
		else return null;
		return "<img src=\"http://api.map.baidu.com/staticimage/v2?ak=vN0BFcVu0YUeFxM00SU5OLwM&width=640&height=425&zoom=15&copyright=1&markerStyles=-1,http://m.renwuto.com/f/ctrl/mapdot.png,-1&center=" + pos + "&markers=" + pos + "\" />";
	};


	me.Ajax = function (url, callback, token, params, get, txt, async) {
		if (!callback) callback = emptyfunc;
		if (!url) callback();
		if (token === true) {
			if (url.indexOf('?') < 0) url += "?tk=" + $$.Vis.Token();
			else if (url[url.length - 1] === "?") url += "tk=" + $$.Vis.Token();
			else url += "&tk=" + $$.Vis.Token();
		}
		var called = false;
		$.ajax({
			method: get === true ? "GET" : "POST",
			url: url,
			data: params,
			dataType: "text",
            xhrFields: {withCredentials: true},
			success: function (text) {
				called = true;
				if (txt !== true) callback($$.Jsonar.parse(text));
				else callback(text);
			},
			error: function (a, b, err) {
			    called = true;
			    console.error(err + "：" + url);
			    callback();
			},
			complete: function () { if (!called) callback(); },
			async: async === false ? false : true,
			cache: true,
			global: false
		});
	};

	var Host = {
		Api: "http://api.renwuto.cn",
		Daili: ""//"http://daili.renwuto.cn"
	};
	var DataUrls = {
	    "dict:cata": Host.Api + "/Dict/Catagory",
	    "dict:area": Host.Api + "/Dict/Area",

	    "dict:prod": Host.Daili + "/api/Dict/Product",
	    "dict:guest": Host.Daili + "/api/Dict/GuestType",
	    "dict:orderstatus": Host.Daili + "/api/Dict/OrderStatus",
	    "dict:orderstatus0": Host.Daili + "/api/Dict/OrderStatus0",
	    "dict:orderstatus1": Host.Daili + "/api/Dict/OrderStatus1",
	    "dict:user": Host.Daili + "/api/Dict/UserType",
	    "dict:bill": Host.Daili + "/api/Dict/BillType",
	    "dict:withdraw": Host.Daili + "/api/Dict/WithdrawStatus",
	    "dict:visrole": Host.Daili + "/api/Dict/VisitorRole",

	    "vis/login": Host.Daili + "/api/Vis/Login",
	    "vis/updpwd": Host.Daili + "/api/Vis/UpdPwd",
	    "vis/get": Host.Daili + "/api/Vis/Get",
	    "vis/ins": Host.Daili + "/api/Vis/Ins",
	    "vis/upd": Host.Daili + "/api/Vis/Upd",

	    "user/get": Host.Daili + "/api/User/Get",
	    "user/updinfo": Host.Daili + "/api/User/UpdInfo",
	    "user/updbusi": Host.Daili + "/api/User/UpdBusi",

	    "order/ins": Host.Daili + "/api/Order/Ins",
	    "order/upd": Host.Daili + "/api/Order/Upd",
	    "order/get": Host.Daili + "/api/Order/Get",
	    "order/list": Host.Daili + "/api/Order/List",
	    "order/getall": Host.Daili + "/api/Order/GetAll",
	    "order/audit20": Host.Daili + "/api/Order/Audit20",
	    "order/audit40": Host.Daili + "/api/Order/Audit40",
	    "order/audit50": Host.Daili + "/api/Order/Audit50",
	    "order/audit60": Host.Daili + "/api/Order/Audit60",
	    "order/audit130": Host.Daili + "/api/Order/Audit130",
	    "order/upd30": Host.Daili + "/api/Order/Upload30",
	    "order/upd100": Host.Daili + "/api/Order/Upload100",

	    "guest/list": Host.Daili + "/api/Guest/List",
	    "guest/get": Host.Daili + "/api/Guest/Get",
	    "guest/gets": Host.Daili + "/api/Guest/Gets",
	    "guest/upd": Host.Daili + "/api/Guest/Upd",
	    "guest/ins": Host.Daili + "/api/Guest/Ins",
	    "guest/del": Host.Daili + "/api/Guest/Del",

	    "with/list": Host.Daili + "/api/Withdraw/List",
	    "with/get": Host.Daili + "/api/Withdraw/Get",
	    "with/getall": Host.Daili + "/api/Withdraw/GetAll",



		Get: function (name) {
		    if (!name) { console.error("$$.GetData name is null"); return null; }
		    var url = this[name.toLowerCase()];
		    if (url) return url;
		    console.error("$$.GetData name invalid：" + name);
		    return null;
		}
	};
	me.GetData = me.SetData = function (api, params, callback, nocache) {
		if (!callback) callback = emptyfunc;
		var url = DataUrls.Get(api); if (!url) { callback(null); return; }
		function addCache(data) {
			var tb = data.cache.name;
			if (!tb) return;

			var id = data.cache.id;
			if (id > 0) {
				me.DB.Set(tb, id, data.row || data.rows, data.cache.expire);
				return;
			}

			var ids = data.cache.ids;
			if (ids && ids.length > 0) {
				var rows = data.rows;
				if (rows && rows.length > 0) me.DB.Sets(tb, ids, rows, data.cache.expire)
				return;
			}

			me.DB.Set(tb, "*", data.row || data.rows, data.cache.expire);
		}
		function getData(stop) {
			me.Ajax(url, function (data) {
				if (!data) { callback(); return; }
				if (!data.success) {
					if (stop !== true && data.code === 15) {
						$$.Vis.Expire();
						$$.Vis.IsLogon(true, function (rst) {
							if (rst) getData(true);
							else callback();
						});
					}
					else callback(data);
					return;
				}
				if (nocache !== true && data.cache) addCache(data);
				callback(data);
			}, true, params);
		}
		getData();
	};
	//获取字典数据
	me.GetDict = function (name, callback, id) {
		if (!callback) callback = emptyfunc;
		if (!name) { callback(); return; }
		name = name.toLowerCase();
		function deal(data) {
			function setIds() {
				var ids = data.ids = {};
				for (var i = 0; i < data.length; i++) {
					var row = data[i];
					if (row) ids["" + row.ID] = row;
				}
			}
			function parent() {
				var ids = data.ids = {};
				var root = data.root = [];
				for (var i = 0; i < data.length; i++) {
					var row = data[i];
					if (!row) continue;
					ids["" + row.ID] = row;
					if (row.Parent === 0) {
						root.push(row);
						continue;
					}
					var prow = ids["" + row.Parent];
					if (!prow) continue;
					row.parentRow = prow;
					if (!prow.childRows) prow.childRows = [];
					prow.childRows.push(row);
				}
			}
			function area() {
				var ids = data.ids = {};
				var hots = data.hots = [];
				var provs = data.provs = [];
				var citys = data.citys = [];
				var baidus = data.baidus = {};
				for (var i = 0; i < data.length; i++) {
					var row = data[i];
					if (!row) continue;
					ids["" + row.ID] = row;
					if (row.Hot) hots.push(row);
					if (row.Baidu) baidus["" + row.Baidu] = row;

					var level = row.Level;
					if (level === 1 || level === 2) provs.push(row);
					else if (level === 3 || level === 4) citys.push(row);

					var prow = ids["" + row.Parent];
					if (!prow) continue;
					row.parentRow = prow;
					if (!prow.childRows) prow.childRows = [];
					prow.childRows.push(row);
				}
			}
			function busi() {
				var ids = data.ids = {};
				var areas = data.areas = {};
				for (var i = 0; i < data.length; i++) {
					var row = data[i];
					if (!row) continue;
					ids["" + row.ID] = row;
					if (!row.Area3) continue;
					var area = areas["" + row.Area3];
					if (!area) area = areas["" + row.Area3] = [];
					area.push(row);
				}
			}

			if (!data || data._inited) return data;
			if (name === "cata") parent();
			else if (name === "area") area();
			else if (name === "busi") busi();
			else setIds();
			data._inited = true;
			me.DB.SetCache("dict", name, data, 300);
			return data;
		}
		me.DB.GetLocal("dict", name, function (dict) {
			if (dict) {
				dict = deal(dict);
				if (!id && id !== 0) callback(dict);
				else if (dict.ids) callback(dict.ids["" + id]);
				else callback(null);
				return;
			}
			var url = DataUrls.Get("dict:" + name); if (!url) { callback(); return; }
			me.Ajax(url, function (data) {
				if (!data || !data.success || !data.rows) { callback(); return; }
				me.DB.SetLocal("dict", name, data = data.rows, 300000);
				dict = deal(data);
				if (!id && id !== 0) callback(dict);
				else if (dict.ids) callback(dict.ids["" + id]);
				else callback(null);
			});
		});
	};
	//获取一条数据
	me.GetRow = function (api, id, callback, tb) {
		if (!callback) callback = emptyfunc;
		if (!api || (!id && id !== 0)) { callback(); return; }
		if (tb) {
			$$.DB.Get(tb, id, function (row) {
				if (row) { callback(row); return; }
				getRow();
				return;
			});
			return;
		}
		getRow();
		function getRow() {
			me.GetData(api, { "@id": id }, function (data) {
				if (!data) data = {};
				if (data.mess) me.Tips(data.mess, 3);
				if (!data.success) {
					callback();
					return;
				}
				if (!data.row) {
					callback();
					return;
				}
				callback(data.row);
			});
		}
	};
	//获取多条数据
	me.GetRows = function (api, ids, callback, tb) {
		if (!callback) callback = emptyfunc;
		if (!api || !ids || ids.length < 1) { callback(); return; }
		if (tb) {
			$$.DB.Gets(tb, ids, function (rows) {
				if (rows === undefined) { callback(); return; }
				if (rows && rows.uns && rows.uns.length < 1) { delete rows.uns; callback(rows); return; }
				getRows(rows);
			});
			return;
		}
		getRows();

		function getRows(rows) {
			if (!rows) rows = [];
			var uns = rows.uns, keys = [];
			if (!uns) {
				uns = []; keys = ids;
				for (var i = 0, len = ids.length; i < len; i++) {
					uns.push(i);
				}
			}
			else {
				for (var i = 0; i < uns.length; i++) {
					keys.push(ids[uns[i]]);
				}
			}
			delete rows.uns;

			$$.GetData(api, { "@ids": keys.join(",") }, function (data) {
				if (!data) { callback(rows); return; }
				if (data.mess) me.Tips(data.mess, 3);
				if (!data.success || !data.rows) { callback(rows); return; }
				var len = Math.min(data.rows.length, keys.length);
				for (var i = 0; i < len; i++) {
					var row = data.rows[i], idx = uns[i];
					if (idx >= 0 && (row || row === 0 || row === false)) rows[idx] = row;
				}
				callback(rows);
			});
		}
	};

	me.ClearCache = function () {
		me.Tips("正在清除缓存,请稍候", 5);
		$$.Shell.ClearCache(function () {
			me.Tips("清除缓存完成");
		});
	};
};